<script setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  artPostManageInfoService,
  artGetArticleInfoService,
  artEditManageInfoService
} from '@/api/article'
import { baseURL } from '@/utils/request'
import axios from 'axios'
const defaultData = {
  id: '',
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
}
const formModel = ref({
  ...defaultData
})

//图片预览
const imgUrl = ref('')
const onSelectFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}

const editRef = ref()

//图片路径转为文件
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}

//暴露函数
const isShow = ref(false)
const showDrawer = async (obj) => {
  isShow.value = true
  if (obj.id) {
    const {
      data: { data }
    } = await artGetArticleInfoService(obj.id)
    formModel.value = data
    formModel.value.cover_img = baseURL + formModel.value.cover_img
    imgUrl.value = formModel.value.cover_img

    // const file=await imageUrlToFile(formModel.value.cover_img,formModel.value.cover_img)
    // FD.append('cover_img',file)
  } else {
    formModel.value = defaultData
    imgUrl.value = ''
    editRef.value.setContents('')
  }
}
defineExpose({
  showDrawer
})

const emits = defineEmits(['success'])
//提交功能
const onPublish = async (state) => {
  formModel.value.state = state
  const FD = new FormData()

  for (let key in formModel.value) {
    FD.append(key, formModel.value[key])
  }
  if (formModel.value.id) {
    await artEditManageInfoService(FD)

    emits('success', 'edit')
  } else {
    await artPostManageInfoService(FD)
    emits('success', 'add')
  }
  isShow.value = false
}
</script>
<template>
  <div class="main1">
    <el-drawer
      v-model="isShow"
      size="40%"
      :title="formModel.id ? '编辑功能' : '添加功能'"
    >
      <el-form :model="formModel" label-width="100px">
        <el-form-item label="文章标题:" prop="title">
          <el-input
            v-model="formModel.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <channel-select
          v-model="formModel.cate_id"
          width="100%"
        ></channel-select>
        <el-form-item label="文章封面:" prop="cover_img">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="onSelectFile"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="文章内容:" prop="content">
          <div class="editor">
            <QuillEditor
              ref="editRef"
              theme="snow"
              v-model:content="formModel.content"
              content-type="html"
            ></QuillEditor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onPublish('已发布')"
            >发布</el-button
          >
          <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.editor {
  width: 100%;
  min-height: 200px;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
